package com.qf.pickname.interceptor;

import com.qf.pickname.entity.Cal;
import com.qf.pickname.utils.HttpCountAndTimeStore;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class Interception02 implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Cal cal = HttpCountAndTimeStore.theRequests.get(request.getRequestURI());
        cal.countAdd();

        System.out.println("==>");
        System.out.println("对路径" + request.getRequestURI() + " 第" + cal.getCount() + "次访问.目前所有所有访问次数:" + cal.getCount());
        long start = System.currentTimeMillis();
        request.setAttribute("start", start);

        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        long end = System.currentTimeMillis();
        long start = (long) request.getAttribute("start");
        Cal cal = HttpCountAndTimeStore.theRequests.get(request.getRequestURI());

        cal.setTimes(cal.getTimes() + end - start);
        if (cal.getTimes() != 0 && cal.getCount() != 0) {
            cal.setAvgTime(cal.getTimes() / cal.getCount());
        }


        System.out.println("本次访问时间为:" + (end - start) + "ms");
        System.out.println("当前总共访问时间:" + cal.getTimes() + "ms");
        System.out.println("访问平均时间为:" + cal.getAvgTime() + "ms");
        System.out.println("<==");

    }


}
